const sql = require('sqlite3').verbose(),
      path = require('path'),
      fs = require('fs');

const databasePath = path.resolve(__dirname, '..', 'data', 'database.db'),
      sqlPath = path.resolve(__dirname, 'sql', 'init.sql');

if(fs.existsSync(databasePath)) {
    console.warn(
        '\n>>>>> WARNING <<<<<',
        '\nDatabase already exists!',
        '\nMake sure it contains no valuable data and delete it manually before initialization!',
        `\nPath to database: ${databasePath}`,
        '\n\n... Initialization aborted ...\n'
    );
} else {
    const db = new sql.Database(databasePath);

    let sqlError = null;

    db.serialize(() => {
        const sql = fs.readFileSync(sqlPath)
            .toString()
            .replace(/(\r\n|\n|\r)/gm," ") // delete new lines
            .replace(/\s+/g, ' ') // delete excess whitespaces
            .split(';')
            .map(Function.prototype.call, String.prototype.trim)
            .filter(q => q.length !== 0);

        for(let query of sql) {
            db.run(query, err => {
                if(err) sqlError = err;
            });
        }
    });

    db.close(() => {
        if(!sqlError) console.log('\nDatabase initialized succesfully!\n');
        else {
            fs.rmSync(databasePath);
            console.error(sqlError);
        }
    });
}
